<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>通知轮询系统测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .notification-panel {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            background-color: #f8f9fa;
        }
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .status-online { background-color: #28a745; }
        .status-offline { background-color: #dc3545; }
        .notification-item {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 12px;
            margin: 8px 0;
        }
        .notification-new {
            border-left: 4px solid #007bff;
            background-color: #f8f9ff;
        }
        .log-area {
            height: 300px;
            overflow-y: auto;
            background: #f8f9fa;
            border: 1px solid #ddd;
            padding: 10px;
            font-family: monospace;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <h1 class="mb-4">通知轮询系统测试</h1>
        
        <!-- 系统状态 -->
        <div class="notification-panel">
            <h3>系统状态</h3>
            <div class="row">
                <div class="col-md-6">
                    <p><span id="pollingStatus" class="status-indicator status-offline"></span>轮询状态: <span id="pollingStatusText">已停止</span></p>
                    <p>轮询间隔: <span id="pollingInterval">3000</span>ms</p>
                    <p>最后检查时间: <span id="lastCheckTime">-</span></p>
                </div>
                <div class="col-md-6">
                    <p>未读通知数: <span id="unreadCount" class="badge bg-primary">0</span></p>
                    <p>总通知数: <span id="totalNotifications" class="badge bg-secondary">0</span></p>
                    <p>错误次数: <span id="errorCount" class="badge bg-danger">0</span></p>
                </div>
            </div>
            <div class="mt-3">
                <button id="startPolling" class="btn btn-success">开始轮询</button>
                <button id="stopPolling" class="btn btn-danger">停止轮询</button>
                <button id="checkNow" class="btn btn-info">立即检查</button>
                <button id="clearLog" class="btn btn-warning">清空日志</button>
            </div>
        </div>
        
        <!-- 通知列表 -->
        <div class="notification-panel">
            <h3>通知列表</h3>
            <div id="notificationsList">
                <p class="text-muted">暂无通知</p>
            </div>
        </div>
        
        <!-- 调试日志 -->
        <div class="notification-panel">
            <h3>调试日志</h3>
            <div id="debugLog" class="log-area"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let pollingInterval = null;
        let pollingIntervalMs = 3000;
        let errorCount = 0;
        let totalNotifications = 0;
        let lastNotifications = [];

        // DOM 元素
        const pollingStatus = document.getElementById('pollingStatus');
        const pollingStatusText = document.getElementById('pollingStatusText');
        const lastCheckTime = document.getElementById('lastCheckTime');
        const unreadCount = document.getElementById('unreadCount');
        const totalNotificationsEl = document.getElementById('totalNotifications');
        const errorCountEl = document.getElementById('errorCount');
        const notificationsList = document.getElementById('notificationsList');
        const debugLog = document.getElementById('debugLog');

        // 按钮事件
        document.getElementById('startPolling').addEventListener('click', startPolling);
        document.getElementById('stopPolling').addEventListener('click', stopPolling);
        document.getElementById('checkNow').addEventListener('click', checkNotifications);
        document.getElementById('clearLog').addEventListener('click', clearLog);

        function log(message) {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}\n`;
            debugLog.textContent += logEntry;
            debugLog.scrollTop = debugLog.scrollHeight;
            console.log(logEntry);
        }

        function updateStatus(isRunning) {
            if (isRunning) {
                pollingStatus.className = 'status-indicator status-online';
                pollingStatusText.textContent = '运行中';
            } else {
                pollingStatus.className = 'status-indicator status-offline';
                pollingStatusText.textContent = '已停止';
            }
        }

        function startPolling() {
            if (pollingInterval) {
                log('轮询已在运行中');
                return;
            }

            log('开始轮询通知...');
            updateStatus(true);
            
            // 立即执行一次
            checkNotifications();
            
            // 设置定时器
            pollingInterval = setInterval(checkNotifications, pollingIntervalMs);
        }

        function stopPolling() {
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
                log('轮询已停止');
                updateStatus(false);
            }
        }

        function checkNotifications() {
            const checkTime = new Date().toLocaleTimeString();
            lastCheckTime.textContent = checkTime;
            
            log('检查通知...');

            // 根据当前页面判断使用哪个API
            const currentPath = window.location.pathname;
            let apiUrl = '/customer/notifications';
            
            // 如果是客服页面，使用客服API
            if (currentPath.includes('/customer-service/')) {
                apiUrl = '/customer-service/notifications';
            }

            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    log(`API响应: ${JSON.stringify(data)}`);
                    
                    if (data.success) {
                        const notifications = data.notifications || [];
                        const currentUnreadCount = data.unreadCount || 0;
                        
                        // 更新统计信息
                        unreadCount.textContent = currentUnreadCount;
                        totalNotifications = notifications.length;
                        totalNotificationsEl.textContent = totalNotifications;
                        
                        // 检查是否有新通知
                        const hasNewNotifications = notifications.length > lastNotifications.length;
                        if (hasNewNotifications) {
                            log(`检测到 ${notifications.length - lastNotifications.length} 条新通知`);
                            showNotificationAlert(notifications[0]);
                        }
                        
                        // 更新通知列表
                        updateNotificationsList(notifications);
                        lastNotifications = notifications;
                        
                        log(`检查完成: ${currentUnreadCount} 条未读通知`);
                    } else {
                        log(`API错误: ${data.message}`);
                        errorCount++;
                        errorCountEl.textContent = errorCount;
                    }
                })
                .catch(error => {
                    log(`请求失败: ${error.message}`);
                    errorCount++;
                    errorCountEl.textContent = errorCount;
                });
        }

        function updateNotificationsList(notifications) {
            if (notifications.length === 0) {
                notificationsList.innerHTML = '<p class="text-muted">暂无通知</p>';
                return;
            }

            let html = '';
            notifications.forEach((notification, index) => {
                const isNew = index === 0 && notifications.length > lastNotifications.length;
                const itemClass = isNew ? 'notification-item notification-new' : 'notification-item';
                
                html += `
                    <div class="${itemClass}">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong>${notification.senderName || '系统'}</strong>
                                <span class="badge bg-info ms-2">${notification.notificationType}</span>
                            </div>
                            <small class="text-muted">${formatTime(notification.createdTime)}</small>
                        </div>
                        <p class="mb-1 mt-2">${notification.messageContent || '无内容'}</p>
                        <small class="text-muted">相关ID: ${notification.relatedId || '-'}</small>
                    </div>
                `;
            });
            
            notificationsList.innerHTML = html;
        }

        function showNotificationAlert(notification) {
            if (notification) {
                // 创建浏览器通知（如果用户允许）
                if (Notification.permission === 'granted') {
                    new Notification(`${notification.senderName} 发送了消息`, {
                        body: notification.messageContent,
                        icon: '/favicon.ico'
                    });
                }
                
                // 在页面上显示提示
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-info alert-dismissible fade show position-fixed';
                alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 300px;';
                alertDiv.innerHTML = `
                    <strong>新通知!</strong><br>
                    ${notification.senderName}: ${notification.messageContent}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.body.appendChild(alertDiv);
                
                // 5秒后自动移除
                setTimeout(() => {
                    if (alertDiv.parentNode) {
                        alertDiv.parentNode.removeChild(alertDiv);
                    }
                }, 5000);
            }
        }

        function formatTime(timeString) {
            if (!timeString) return '-';
            try {
                const date = new Date(timeString);
                return date.toLocaleString('zh-CN');
            } catch (e) {
                return timeString;
            }
        }

        function clearLog() {
            debugLog.textContent = '';
            errorCount = 0;
            errorCountEl.textContent = '0';
            log('日志已清空');
        }

        // 请求通知权限
        if (Notification.permission === 'default') {
            Notification.requestPermission().then(permission => {
                log(`通知权限: ${permission}`);
            });
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('通知轮询测试页面已加载');
            log(`当前页面: ${window.location.pathname}`);
            
            // 检查一次当前状态
            checkNotifications();
        });

        // 页面卸载时停止轮询
        window.addEventListener('beforeunload', function() {
            stopPolling();
        });
    </script>
</body>
</html> 